/**
 * Created by apple on 16/3/31.
 */
class Controller {
    constructor (systemService, statusMap, uiNotification,$modalInstance, item) {
        "ngInject"
        this.uiModal = $modalInstance;
        this.service = systemService;
        this.notify  = uiNotification;
        this.status  = statusMap;
        this.isEdit  = item.type == 'edit' ? true : false;
        this.data    = this.isEdit ? angular.copy(item.node) :{ statusCd: "S0A", parRegionId: item.node.id, regionType: item.node.regionType == 1100 ? ~~item.node.regionType + 200 : ~~item.node.regionType + 100};
        this.type    = this.isEdit ? 'update' : 'insert';
    }

    checkSame () {
        if (!this.isEdit) {
            if (this.data.regionName) {
                this.service.checkExist('region',{
                    regionName: this.data.regionName,
                    parRegionId: this.data.parRegionId
                }).then((res) => {
                    this.isSame = res.data;
                    if (res.data) {
                        this.notify.error({
                            'title'  : '提示',
                            'message': '存在同名组织, 不可重复添加!'
                        });
                    }
                })
            }
        }
    }

    save () {
        if ( this.submitting ) return;
        this.submitting = true;

        this.service[this.type]('region', this.data).then((r) => {
            this.data.id = r.data;
            this.uiModal.close(this.data);
            this.notify.success({
                'title'  : '提示',
                'message': '操作成功!'
            });
        }).catch((data) => {
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
            });
        }).finally(() => {
            // 隐藏 loading
            this.submitting = false;
        });
    }
    cancel () {
        this.uiModal.dismiss('cancel')
    }
}

export default Controller;